from typing import Optional

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.tools_apollo.handlers import apollo_search, apollo_app_name
from app.tools_apollo.utils import get_db
from core.response import resp_200, resp_400
from core.logger import logger
from core.security import permission_checker
router = APIRouter()


@router.get('/app_name', summary="应用服务列表信息", description="工具-apollo配置查询")
async def get_apollo_app_name(db: Session = Depends(get_db), user=Depends(permission_checker)):
    result = apollo_app_name(db)
    if not result:
        message = "get apollo config app list"
        logger.error(f"{message}")
        return resp_400(message)
    return resp_200(result)


@router.get('/', summary="应用服务配置查询", description="工具-apollo配置查询")
async def get_apollo_search(db: Session = Depends(get_db),
                                  app_name: str = Query('all', description="应用服务名称"),
                                  key: Optional[str] = Query(None, description="应用服务配置key"),
                                  value: str = Query(..., description="应用服务配置value"),
                                  page: int = Query(1, ge=1),
                                  per_page: int = Query(10, ge=0), user=Depends(permission_checker)):
    result = apollo_search(db, app_name=app_name, key=key, value=value, page=page, per_page=per_page)
    if not result:
        message = "get apollo config search failed"
        logger.error(
            f"{message} => page:{page} per_page:{per_page} app_name:{app_name} key:{key} value:{value}")
        return resp_400(message)
    return resp_200(result)
